import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_baidu_mapapi_search/flutter_baidu_mapapi_search.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';

import 'plugin_constant_util.dart';

class CenterLocationPage extends StatefulWidget {
  bool? isEdit;
  double? appBarElevation;
  Color? appBarBg;
  String? latitude;
  String? longitude;
  String? address;
  String? icon_location;

  CenterLocationPage({
    this.isEdit,
    this.appBarElevation,
    this.appBarBg,
    this.latitude,
    this.longitude,
    this.address,
    this.icon_location,
    // this.addressVo
  });
  @override
  State<CenterLocationPage> createState() => _CenterLocationPageState();
}

class _CenterLocationPageState extends State<CenterLocationPage> {
  Size? screenSize;
  BMFMapController? myMapController;
  //检索的点的地址数据控制器
  StreamController<Map<String,dynamic>> dataControl=StreamController();
  //检索的点的地址数据
  Map<String,dynamic> dataMap=Map();

  LocationFlutterPlugin locationPlugin = new LocationFlutterPlugin();
  //定位的数据控制器
  StreamSubscription<Map<String, Object>>? locationListener;
  BaiduLocation? baiduLocation; // 定位结果

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initParms();
  }
  initParms()async{
    ///单次定位时如果是安卓可以在内部进行判断调用连续定位
    if (Platform.isIOS) {
      ///接受定位回调
      locationPlugin.singleLocationCallback(callback: (BaiduLocation result) {
        print('_locationPlugin-->result=${result?.getMap()}');
        try {
          baiduLocation = result;
          myMapController?.setCenterCoordinate(
              BMFCoordinate(baiduLocation?.latitude??0, baiduLocation?.longitude??0), false,
              animateDurationMs: 1);
          dataMap={'regionName':baiduLocation?.address,'sematicDescription':baiduLocation?.address,
            'latitude':'${baiduLocation?.latitude}','longitude':'${baiduLocation?.longitude}'};
        } catch (e) {
          print(e);
        }
        setState(() {});
      });
    } else if (Platform.isAndroid) {
      ///接受定位回调
      locationPlugin.seriesLocationCallback(callback: (BaiduLocation result) {
        print('_locationPlugin-->result=${result?.getMap()}');
        try {
          baiduLocation = result;
          myMapController?.setCenterCoordinate(
              BMFCoordinate(baiduLocation?.latitude??0, baiduLocation?.longitude??0), false,
              animateDurationMs: 1);
          locationPlugin.stopLocation();
          dataMap={'regionName':baiduLocation?.address,'sematicDescription':baiduLocation?.address,
            'latitude':'${baiduLocation?.latitude}','longitude':'${baiduLocation?.longitude}'};
        } catch (e) {
          print(e);
        }
        setState(() {});
      });
    }
    // //接受定位回调
    // locationPlugin.seriesLocationCallback(callback: (BaiduLocation result) {
    //   print('_locationPlugin-->result=$result');
    //   try {
    //     baiduLocation = result;
    //     myMapController?.setCenterCoordinate(
    //         BMFCoordinate(baiduLocation?.latitude??0, baiduLocation?.longitude??0), false,
    //         animateDurationMs: 1);
    //
    //   } catch (e) {
    //     print(e);
    //   }
    //   setState(() {});
    // });

    dataControl?.stream?.listen((event) {
      dataMap=event??{};
      setState(() {});
    });
    if(isLatLongValidate(widget.latitude,widget.longitude)){
      //只有经纬度传过来,进行经纬度赋值
      print('toMap--只有经纬度传过来-->isEdit=${widget.isEdit},latitude=${widget.latitude},longitude=${widget.longitude}');
      _getLocationBylatLon(widget.latitude,widget.longitude,'');
    }else{
      //什么都没有传过来，直接进行定位当前位置
      print('toMap--什么都没有传过来,直接进行定位当前位置');
      _startLocation();
    }
  }
  //经纬度是否可用
  isLatLongValidate(dynamic latitudeCur,dynamic longitudeCur,){
    return
      (('${latitudeCur??''}').isNotEmpty&&('${latitudeCur??''}'!='null')&&('${latitudeCur??''}'!='0')
          &&('${longitudeCur??''}'!='0')&&('${longitudeCur??''}'!='null')&&('${longitudeCur??''}').isNotEmpty);
  }
  void _getLocationBylatLon(String? latitudeCur, String? longitudeCur,String? addrDescriptionCur) {
    var locationJson={'regionName':'','sematicDescription':addrDescriptionCur,
      'latitude':'${latitudeCur}','longitude':'${longitudeCur}'};
    dataControl.sink.add(locationJson);

    if((latitudeCur=='')||(latitudeCur==null)||(latitudeCur=='null'))latitudeCur='0';
    if((longitudeCur=='')||(longitudeCur==null)||(longitudeCur=='null'))longitudeCur='0';

    baiduLocation = BaiduLocation(latitude:double.parse('$latitudeCur'),longitude:  double.parse('$longitudeCur'));
    setState(() {});
    if(isLatLongValidate(latitudeCur,longitudeCur)){
      getAddressByCordinat(double.parse('$latitudeCur'), double.parse('$longitudeCur'), (Map<String,dynamic> locationJson){
        dataControl.sink.add(locationJson);
        print('_onGetReverseGeoCodeSearchResult-->locationJson=$locationJson');
      });
    }else{
      // showToastWidget(CustomToastAlertWidget(
      //   alertTitle: "无效地址！",
      // ));
    }
  }

  @override
  void dispose() {
    _stopLocation();
    if(dataControl!=null)dataControl.close();
    super.dispose();
  }
  // /// 启动定位
  Future<void> _location() async {
    print('定位');
    await _stopLocation();
    await _startLocation();
  }
  // /// 启动定位
  Future<void> _startLocation() async {
    await _locationAction();
    if (Platform.isIOS) {
      var _suc = await locationPlugin
          .singleLocation({'isReGeocode': true, 'isNetworkState': true});
      print('开始单次定位：$_suc');
    } else if (Platform.isAndroid) {
     var _suc = await locationPlugin.startLocation();
      print('开始安卓单次定位：$_suc');
    }
  }

  /// 停止定位
  Future<void> _stopLocation() async {
    await locationPlugin?.stopLocation();
  }
  _locationAction() async {
    /// 设置android端和ios端定位参数
    /// android 端设置定位参数
    /// ios 端设置定位参数
    Map iosMap = initIOSOptions().getMap();
    Map androidMap = initAndroidOptions().getMap();

    await locationPlugin?.prepareLoc(androidMap, iosMap);
    print('设置定位参数：$iosMap');
  }

  /// 设置地图参数
  BaiduLocationAndroidOption initAndroidOptions() {
    BaiduLocationAndroidOption options = BaiduLocationAndroidOption(
        coorType: 'bd09ll',
        locationMode: BMFLocationMode.hightAccuracy,
        isNeedAddress: true,
        isNeedAltitude: true,
        isNeedLocationPoiList: true,
        isNeedNewVersionRgc: true,
        isNeedLocationDescribe: true,
        openGps: true,
        locationPurpose: BMFLocationPurpose.sport,
        coordType: BMFLocationCoordType.bd09ll);
    return options;
  }

  BaiduLocationIOSOption initIOSOptions() {
    BaiduLocationIOSOption options = BaiduLocationIOSOption(
        coordType: BMFLocationCoordType.bd09ll,
        BMKLocationCoordinateType: 'BMKLocationCoordinateTypeBMK09LL',
        desiredAccuracy: BMFDesiredAccuracy.best);
    return options;
  }
  @override
  Widget build(BuildContext context) {
    screenSize = MediaQuery.of(context).size;
    return  Scaffold(
      appBar: AppBar(
        centerTitle: true,
        elevation: widget.appBarElevation??0,
        backgroundColor: widget.appBarBg??Color(0xFFB3895D),
        title: Text('地图'),
        actions: (!(widget.isEdit??false))?[]:[
          Container(
            width: 60,
            child: MaterialButton(
              padding: EdgeInsets.only(),
              child: Text(
                '确定',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 14
                ),
              ),
              onPressed: ()=>_save(),
            ),
          ),
          SizedBox(width: 10,),
        ],
      ),
      body: Column(
        children: [
          Expanded(child: Stack(children: <Widget>[
            generateMap(),
            Align(
              child:
              // (widget.icon_location??'').isNotEmpty?
              // Image.asset(widget.icon_location,width: 18,):
              Image.asset('${PluginConstantUtil.img_base_url}/icon_location.png',width: 18,),
            ),
            Positioned(
              right: 22,
              bottom: 180,
              child: InkWell(
                onTap: ()=>_location(),
                child: Container(
                  padding: EdgeInsets.all(6),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(5))
                  ),
                  child: Image.asset('${PluginConstantUtil.img_base_url}/icon_map_btn_location.png',width: 26,),
                ),
              ),
            ),
          ])),
          Visibility(
              visible: ('${dataMap['regionName']??''}').isNotEmpty
                  ||('${dataMap['sematicDescription']??''}').isNotEmpty||('${dataMap['latitude']??''}').isNotEmpty||('${dataMap['longitude']??''}').isNotEmpty,
              child: Container(
                  color: Colors.white,
                  // height: 80,
                  padding: EdgeInsets.only(
                    left: 15,
                    right: 15,
                    top: 12,
                    bottom: 12,
                  ),
                  width: MediaQuery.of(context).size.width,
                  child: (('${dataMap['regionName']??''}').isNotEmpty||('${dataMap['sematicDescription']??''}').isNotEmpty)?
                  Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '${dataMap['regionName']??''}',
                        style: TextStyle(
                            fontWeight: FontWeight.w600
                        ),
                      ),
                      SizedBox(
                        height: 5,
                      ),
                      Text(
                        '${dataMap['sematicDescription']??''}',
                      ),
                    ],
                  ):
                  Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '经度：${dataMap['longitude']??''}',
                        style: TextStyle(
                            fontWeight: FontWeight.w600
                        ),
                      ),
                      SizedBox(
                        height: 5,
                      ),
                      Text(
                        '纬度：${dataMap['latitude']??''}',
                      ),
                    ],
                  )
              )
          )
        ],
      ),
    );
  }
  /// 创建地图
  Container generateMap() {
    return Container(
      height: screenSize?.height,
      width: screenSize?.width,
      child: BMFMapWidget(
        onBMFMapCreated: onBMFMapCreated,
        mapOptions: initMapOptions(),
      ),
    );
  }

  /// 创建完成回调
  void onBMFMapCreated(BMFMapController controller) {
    myMapController = controller;
    myMapController?.cleanAllMarkers();
    //设置地图监听
    setMapLisener();
  }
  void setMapLisener() {
    /// 地图加载回调
    myMapController?.setMapDidLoadCallback(callback: () {
      print('mapDidLoad-地图加载完成');
    });
    /// 地图区域改变完成后会调用此接口
    /// mapStatus 地图状态信息
    myMapController?.setMapRegionDidChangeWithReasonCallback(callback: (BMFMapStatus mapStatus, BMFRegionChangeReason regionChangeReason) {
      if (BMFRegionChangeReason.Gesture == regionChangeReason) {
        //地理中心点坐标
        double level = 12;
        BMFCoordinate? targetGeoPt = mapStatus.targetGeoPt;
        print('myMapController-->level=${level}');
        print('myMapController-->targetGeoPt=${targetGeoPt?.toMap()}');

        getAddressByCordinat(targetGeoPt?.latitude??0, targetGeoPt?.longitude??0, (Map<String,dynamic> locationJson){
          dataControl.sink.add(locationJson);
          print('_onGetReverseGeoCodeSearchResult-->locationJson=$locationJson');
        });
      }
    });
  }
  BMFMapOptions initMapOptions() {
    BMFCoordinate center = BMFCoordinate(baiduLocation?.latitude??0, baiduLocation?.longitude??0);
    BMFMapOptions mapOptions = BMFMapOptions(
        mapType: BMFMapType.Standard,
        zoomLevel: getInitLevel(),
        maxZoomLevel: 21,
        minZoomLevel: 8,
        // backgroundColor: Colors.blue,
        logoPosition: BMFLogoPosition.LeftBottom,
        mapPadding: BMFEdgeInsets(top: 0, left: 50, right: 50, bottom: 0),
        overlookEnabled: true,
        overlooking: -15,
        center: center);
    return mapOptions;
  }
  getInitLevel() {
    if(
    isLatLongValidate(widget.latitude,widget.longitude)
    )return 20;
    return 21;
  }
  //逆地理转换
  getAddressByCordinat(double latitude,double longitude,Function onResult) async{
    /// 检索参数
    BMFCoordinate coordinate = BMFCoordinate(latitude, longitude);
    BMFReverseGeoCodeSearchOption option = BMFReverseGeoCodeSearchOption(location: coordinate);
    option.isLatestAdmin = true;

    /// 检索对象
    BMFReverseGeoCodeSearch reverseGeoCodeSearch = BMFReverseGeoCodeSearch();

    /// 注册检索回调
    reverseGeoCodeSearch.onGetReverseGeoCodeSearchResult(callback: (BMFReverseGeoCodeSearchResult result, BMFSearchErrorCode errorCode) {
      print("发起检索成功————>onGetReverseGeoCodeSearchResult=${result?.toMap()}");
      if (errorCode != BMFSearchErrorCode.NO_ERROR) {
        var error = "检索失败" + "errorCode:${errorCode.toString()}";
        // showToastWidget(CustomToastAlertWidget(
        //   alertTitle: error,
        // ));
        Map<String,dynamic> locationJson={'regionName':null,'sematicDescription':null,
          'latitude':latitude,'longitude':longitude};
        if(onResult!=null)onResult(locationJson);
        print(error);
        return;
      }
      /// 检索结果 alert msg
      Map resultMap = result.toMap();
      print("发起检索成功————>$resultMap");
      if((resultMap!=null)&&(resultMap is Map)){
        var poiRegions = resultMap['poiRegions']??[];
        var location = resultMap['location']??{};
        var sematicDescription = resultMap['sematicDescription'];
        var regionName='';
        if((poiRegions!=null)&&(poiRegions is List)&&(poiRegions.length>0)){
          regionName = poiRegions[0]['regionName'];
        }
        Map<String,dynamic> locationJson={'regionName':regionName,'sematicDescription':sematicDescription,
          'latitude':location['latitude'],'longitude':location['longitude']};
        if(onResult!=null)onResult(locationJson);
        // print('_onGetReverseGeoCodeSearchResult-->resultMap=$resultMap');
      }
    });

    /// 发起检索
    print("开始发起检索--->latitude=$latitude,longitude=$longitude");
    bool result = await reverseGeoCodeSearch.reverseGeoCodeSearch(option);
    if (result) {
      print("发起检索成功");
    } else {
      print("发起检索失败");
      if(onResult!=null)onResult(null);
    }
  }

  _save() {
    // addressVo
    if(dataMap==null)dataMap= {};
    String address = '${dataMap['sematicDescription']}';
    String latitude = '${dataMap['latitude']}';
    String longitude = '${dataMap['longitude']}';
    Navigator.pop(context,{'latitude':latitude,'longitude':longitude,'address':address,});
  }
}
